package com.example.demo.service.impl;

import com.example.demo.service.DataAnalysisService;
import com.example.demo.vo.DataAnalysisVO;
import com.example.demo.mapper.ChildMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.entity.User;
import com.example.demo.entity.Child;
import com.example.demo.entity.GrowthRecord;
import com.example.demo.mapper.GrowthRecordMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
import java.time.Period;
import java.time.LocalDate;
import java.util.Date;

/**
 * 数据分析服务实现类
 */
@Service
@RequiredArgsConstructor
public class DataAnalysisServiceImpl implements DataAnalysisService {

    private final UserMapper userMapper;
    private final ChildMapper childMapper;
    private final GrowthRecordMapper growthRecordMapper;

    @Override
    public DataAnalysisVO getAnalysisData() {
        DataAnalysisVO vo = new DataAnalysisVO();
        
        // 1. 获取用户总数
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getStatus, 1);
        long totalUsers = userMapper.selectCount(userWrapper);
        vo.setTotalUsers((int) totalUsers);
        
        // 2. 获取本月新增用户数
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime monthStart = now.with(TemporalAdjusters.firstDayOfMonth());
        LocalDateTime monthEnd = now.with(TemporalAdjusters.lastDayOfMonth());
        
        LambdaQueryWrapper<User> monthlyUserWrapper = new LambdaQueryWrapper<>();
        monthlyUserWrapper.eq(User::getStatus, 1)
                         .between(User::getCreateTime, monthStart, monthEnd);
        long monthlyNewUsers = userMapper.selectCount(monthlyUserWrapper);
        vo.setMonthlyNewUsers((int) monthlyNewUsers);
        
        // 3. 获取最新生长记录数据统计
        LambdaQueryWrapper<GrowthRecord> recordWrapper = new LambdaQueryWrapper<>();
        recordWrapper.orderByDesc(GrowthRecord::getRecordTime);
        List<GrowthRecord> allRecords = growthRecordMapper.selectList(recordWrapper);
        
        // 计算平均身高和体重
        if (!allRecords.isEmpty()) {
            double avgHeight = allRecords.stream()
                .mapToDouble(r -> r.getHeight().doubleValue())
                .average()
                .orElse(0.0);
            
            double avgWeight = allRecords.stream()
                .mapToDouble(r -> r.getWeight().doubleValue())
                .average()
                .orElse(0.0);
                
            vo.setAverageHeight(BigDecimal.valueOf(avgHeight)
                .setScale(1, RoundingMode.HALF_UP).doubleValue());
            vo.setAverageWeight(BigDecimal.valueOf(avgWeight)
                .setScale(1, RoundingMode.HALF_UP).doubleValue());
        }
        
        // 4. 计算身高、体重、BMI分布
        List<Integer> heightDistribution = new ArrayList<>();
        List<Integer> weightDistribution = new ArrayList<>();
        List<Integer> bmiDistribution = new ArrayList<>();
        List<Integer> ageDistribution = new ArrayList<>();
        
        // 初始化分布数组
        for (int i = 0; i < 5; i++) {
            heightDistribution.add(0);
            weightDistribution.add(0);
            bmiDistribution.add(0);
            ageDistribution.add(0);
        }
        
        // 统计身高、体重、BMI分布
        for (GrowthRecord record : allRecords) {
            // 身高分布 (<80cm, 80-100cm, 100-120cm, 120-140cm, >140cm)
            double height = record.getHeight().doubleValue();
            if (height < 80) heightDistribution.set(0, heightDistribution.get(0) + 1);
            else if (height < 100) heightDistribution.set(1, heightDistribution.get(1) + 1);
            else if (height < 120) heightDistribution.set(2, heightDistribution.get(2) + 1);
            else if (height < 140) heightDistribution.set(3, heightDistribution.get(3) + 1);
            else heightDistribution.set(4, heightDistribution.get(4) + 1);
            
            // 体重分布 (<10kg, 10-20kg, 20-30kg, 30-40kg, >40kg)
            double weight = record.getWeight().doubleValue();
            if (weight < 10) weightDistribution.set(0, weightDistribution.get(0) + 1);
            else if (weight < 20) weightDistribution.set(1, weightDistribution.get(1) + 1);
            else if (weight < 30) weightDistribution.set(2, weightDistribution.get(2) + 1);
            else if (weight < 40) weightDistribution.set(3, weightDistribution.get(3) + 1);
            else weightDistribution.set(4, weightDistribution.get(4) + 1);
            
            // BMI分布 (<14, 14-16, 16-18, 18-20, >20)
            if (record.getBmi() != null) {
                double bmi = record.getBmi().doubleValue();
            if (bmi < 14) bmiDistribution.set(0, bmiDistribution.get(0) + 1);
            else if (bmi < 16) bmiDistribution.set(1, bmiDistribution.get(1) + 1);
            else if (bmi < 18) bmiDistribution.set(2, bmiDistribution.get(2) + 1);
            else if (bmi < 20) bmiDistribution.set(3, bmiDistribution.get(3) + 1);
            else bmiDistribution.set(4, bmiDistribution.get(4) + 1);
            }
        }
        
        // 5. 计算年龄分布
        LambdaQueryWrapper<Child> childWrapper = new LambdaQueryWrapper<>();
        List<Child> allChildren = childMapper.selectList(childWrapper);
        
        for (Child child : allChildren) {
            Date birthday = child.getBirthday();
            if (birthday != null) {
                LocalDate birthDate = new java.sql.Date(birthday.getTime())
                    .toLocalDate();
                int age = Period.between(birthDate, LocalDate.now()).getYears();
                
                // 年龄分布 (0-1岁, 1-3岁, 3-6岁, 6-12岁, >12岁)
                if (age <= 1) ageDistribution.set(0, ageDistribution.get(0) + 1);
                else if (age <= 3) ageDistribution.set(1, ageDistribution.get(1) + 1);
                else if (age <= 6) ageDistribution.set(2, ageDistribution.get(2) + 1);
                else if (age <= 12) ageDistribution.set(3, ageDistribution.get(3) + 1);
                else ageDistribution.set(4, ageDistribution.get(4) + 1);
            }
        }
        
        // 设置分布数据
        vo.setHeightDistribution(heightDistribution);
        vo.setWeightDistribution(weightDistribution);
        vo.setBmiDistribution(bmiDistribution);
        vo.setAgeDistribution(ageDistribution);
        
        // 6. 计算月度增长率
        if (totalUsers > 0) {
            LocalDateTime lastMonthStart = monthStart.minusMonths(1);
            LocalDateTime lastMonthEnd = monthStart.minusDays(1);
            
            LambdaQueryWrapper<User> lastMonthWrapper = new LambdaQueryWrapper<>();
            lastMonthWrapper.eq(User::getStatus, 1)
                          .le(User::getCreateTime, lastMonthEnd);
            long lastMonthUsers = userMapper.selectCount(lastMonthWrapper);
            
            if (lastMonthUsers > 0) {
                double growthRate = ((double) (totalUsers - lastMonthUsers) / lastMonthUsers) * 100;
                vo.setMonthlyGrowthRate(BigDecimal.valueOf(growthRate)
                    .setScale(2, RoundingMode.HALF_UP).doubleValue());
            }
        }
        
        return vo;
    }
} 